package com.carassistant.beta.phone;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Pattern;

import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

import com.carassistant.beta.R;
import com.carassistant.beta.common.CarAssistantActivity;
import com.carassistant.beta.phone.adapter.ContactAdapter;
import com.carassistant.beta.phone.baseview.LetterView;
import com.carassistant.beta.phone.baseview.LetterView.OnTouchingLetterChangedListener;

public class PhoneContactActivity extends CarAssistantActivity implements OnItemClickListener{
	public static final String ID = "id";
	public static final String NAME = "name";  
	public static final String NUMBER = "number";
	public static final String SORT_KEY = "sort_key";
	public static final int TOKEN_ONCREATE = 0;
	public static final int TOKEN_UPDATE = 1;
       
    private ListView personList;
    private TextView overlay;
    private LetterView letterListView;
    private AsyncQueryHandler asyncQuery;  
    
    private HashMap<String, Integer> alphaIndex;//存放存在的汉语拼音首字母和与之对应的列表位置 
    private Handler handler; 
    private boolean isGetNumber = false;
    
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.phone_contact);  
        
        personList = (ListView) findViewById(R.id.list_view);
        personList.setOnItemClickListener(this);
        letterListView = (LetterView) findViewById(R.id.MyLetterListView01);
        letterListView.setOnTouchingLetterChangedListener(new LetterListViewListener());
		
        asyncQuery = new MyAsyncQueryHandler(getContentResolver()); 
        initHandler();
        initOverlay();
        
        int requirCode = getIntent().getIntExtra(PhoneFavActivity.REQUEIR_NUMBER, -1); 
		if (requirCode != -1) { 
			isGetNumber = true;
		}  
		getContacts(TOKEN_ONCREATE); 
    }  
  
    private void initHandler(){
    	handler = new Handler(){
        	public void handleMessage(android.os.Message msg) {
        		if (msg.what == 0) {
        			overlay.setVisibility(View.INVISIBLE);
				}
        	};
        }; 
    }
    
    /**
     * 异步查询所有联系人
     * @param int
     * */
    private void getContacts(int token){
    	String[] projection = {
				ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
				ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
				ContactsContract.CommonDataKinds.Phone.NUMBER,
				ContactsContract.CommonDataKinds.Phone.TYPE, "sort_key" };
		asyncQuery.startQuery(token, null,
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,
				null, null, "sort_key COLLATE LOCALIZED asc");
    }
    
    @Override
    protected void onRestart() { 
    	super.onRestart();
    	getContacts(TOKEN_UPDATE);
    }
    
    //查询联系人
    private class MyAsyncQueryHandler extends AsyncQueryHandler {  
        public MyAsyncQueryHandler(ContentResolver cr) {  
            super(cr);  
  
        }  
  
        @Override  
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {  
            if (cursor != null && cursor.getCount() > 0) {  
            	ArrayList<ContentValues> list = new ArrayList<ContentValues>();
            	int preID = 0;
                while (cursor.moveToNext()) {
                	int id = cursor.getInt(0);  
            		ContentValues cv = new ContentValues();    
                    String name = cursor.getString(1);
                    String number = cursor.getString(2);
                    String sortKey = cursor.getString(4);
                    int typePhone = ContactsContract.CommonDataKinds. Phone.getTypeLabelResource(cursor.getInt(3)); 
                    cv.put(ID, id);
                    cv.put(NAME, name); 
                    cv.put(NUMBER, getString(typePhone) +":"+ number);
                    cv.put(SORT_KEY, sortKey); 
                    list.add(cv); 
                }  
                if (list.size() > 0) {  
                    setAdapter(list, token);  
                }
                
                cursor.close();
            }  
        }  
  
    }  
  
    private void setAdapter(ArrayList<ContentValues> list, int token) { 
    	if (list == null || list.size() == 0) {
			return;
		}
    	
    	alphaIndex = new HashMap<String, Integer>();
    	int size = list.size();
    	for (int i = 0; i < size; i++) { 
			String currentStr = getAlpha(list.get(i).getAsString(SORT_KEY)); 
			String previewStr = (i - 1) >= 0 ? getAlpha(list.get(i - 1)
					.getAsString(SORT_KEY)) : " ";
			if (!previewStr.equals(currentStr)) { 
				alphaIndex.put(currentStr, i); 
			}
		}  
    	if (token == TOKEN_ONCREATE) {
    		personList.setAdapter(new ContactAdapter(this, list));  
		} else if (token == TOKEN_UPDATE && personList != null) {
			((ContactAdapter)personList.getAdapter()).notifyData(list);
		}
        
    }
    
    //获得汉语拼音首字母 
    private String getAlpha(String str) {  
        if (str == null || str.trim().length() == 0) {  
            return "#";  
        }   
        
        char c = str.trim().charAt(0);   
        Pattern pattern = Pattern.compile("^[A-Za-z]+$");  
        if (pattern.matcher(c + "").matches()) {  
            return (c + "").toUpperCase();  
        } else {  
            return "#";  
        }  
    }
    
    //初始化汉语拼音首字母弹出提示框
    private WindowManager windowManager;
    private void initOverlay() {
    	LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
    	overlay = (TextView) inflater.inflate(R.layout.overlay, null);
    	overlay.setBackgroundColor(R.color.head_color);
    	overlay.setVisibility(View.INVISIBLE);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
						| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
				PixelFormat.TRANSLUCENT);
		windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
		windowManager.addView(overlay, lp);
    }
    
    private class LetterListViewListener implements OnTouchingLetterChangedListener{

		@Override
		public void onTouchingLetterChanged(final String s) {
			if(alphaIndex != null && alphaIndex.get(s) != null) {
				if (personList != null) {
					int position = alphaIndex.get(s);
					personList.setSelection(position);
					overlay.setText(s);
					overlay.setVisibility(View.VISIBLE);  
					handler.sendEmptyMessageDelayed(0, 1500);
				} 
			} 
		} 
    }

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) { 
		ContentValues values = (ContentValues) parent.getAdapter().getItem(position);
		String name = values.getAsString(NAME);
		String number = values.getAsString(NUMBER);

		int _id = values.getAsInteger(ID);
		if (isGetNumber) {
			Intent data = new Intent();
			data.putExtra(ID, _id);
			data.putExtra(NAME, name);
			data.putExtra(NUMBER, number);
			setResult(PhoneFavActivity.RESULT_NUMBER_CODE, data);
			finish();
		} else {
			dailNumber(number);
		} 
	}  
	
	/**
	 * 调用系统的拨号功能
	 * @param number
	 * */
	private void dailNumber(String number){
		if (number != null && !"".equals(number)) {
			Uri callUri = Uri.parse("tel:" + number);
			startActivity(new Intent(Intent.ACTION_CALL, callUri));
		} 
	}
	
	@Override
	protected void onDestroy() { 
		super.onDestroy();
		if (alphaIndex != null) {
			alphaIndex.clear();
			alphaIndex = null;
		}
		windowManager.removeView(overlay);
	}
}
